﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectPool : MonoBehaviour
{
    private Dictionary<string, Queue<GameObject>> pool = new Dictionary<string, Queue<GameObject>>();

    public void Push(GameObject _object)
    {
        string _root = _object.name.Replace("(Clone)", string.Empty);
        if (!pool.ContainsKey(_root))
        {
            pool.Add(_root, new Queue<GameObject>());
            GameObject gameObject = new GameObject(_root);
            gameObject.transform.SetParent(transform);
        }
        _object.SetActive(false);
        pool[_root].Enqueue(_object);
    }

    public GameObject Pop(GameObject _object)
    {
        string _root = _object.name.Replace("(Clone)", string.Empty);
        if (!pool.ContainsKey(_root) || pool[_root].Count < 1)
        {
            Push(Instantiate(_object));
        }

        GameObject gameObject = pool[_root].Dequeue();

        gameObject.SetActive(true);
        return gameObject;
    }
}
